<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\common\Mdatatoe;

class Timer extends Command
{
    protected $timer;

    protected $interval =1800;

    protected function configure()
    {
        // 指令配置
        $this->setName('timer')
            ->addArgument('status',Argument::REQUIRED, 'start/stop/reload/status/connections')
            ->addOption('d',null,Option::VALUE_NONE,'daemon方式启动')
            ->addOption('i',null,Option::VALUE_OPTIONAL,'多长时间执行一次')
            ->setDescription('the timer command');
    }

    protected function init(Input $input, Output $output)
    {
        Global $argv;

        if($input->hasOption(i)){
            $this->interval = floatval($input->getOption('i'));
        }
        $argv[1] = $input->getArgument('status')?:'start';
        if($input->hasOption('d')){
            $argv[2] = '-d';
        }else{
            unset($argv[2]);
        }
    }

    protected function execute(Input $input, Output $output)
    {
    	// 指令输出
      $this->init($input, $output);
      if($argv[1] == 'stop'){
          $this->stop();
          $output->writeln("定时写入任务已停止");
          return;
      }
      $task=new Worker();
      $task->count=1;
      $task->onWorkerStart=[$this,'start'];
      $task->runAll();
    	//$output->writeln('timer');
    }

    public function stop()
    {
        \Workerman\Lib\Timer::del($this->timer);
    }

    public function start()
    {
        $last=time();
        $this->timer = \Workerman\Lib\Timer::add($this->interval, function() use (&$task){
            try {
                //执行elasticsearch数据写入数据表写入操作
            } catch(\Throwable $e){

            }
        });
    }
}
